const {
	getList,
	getDetail,
	newBlog,
	updataBlog,
	delBlog
} = require("../controller/blog.js");
const {
	SuccModel,
	ErrModel
} = require("../model/resModel.js");

// 统一的登陆验证
const islogin = (req) => {
	if(!req.session.username){
		return Promise.resolve(new ErrModel('没有登录'));
	}
};


const blogRouter = (req, res) => {
	const method = req.method;
	const id = req.query.id;
 
	// 获取博客列表
	if (method === "GET" && req.path === "/api/blog/list") {
		const author = req.query.author || "";
		const keyword = req.query.keyword || "";
		// const listData = getList(author, keyword)
		// return new SuccModel(listData)
		const result = getList(author, keyword);
		return result.then(listData => {
			return new SuccModel(listData);
		});
	}

	// 获取博客详情
	if (method === "GET" && req.path === "/api/blog/detail") {
		const data = getDetail(id);
		return data.then(e => {
			return new SuccModel(e);
		});
	}



	// 新建博客
	if (method === "POST" && req.path === "/api/blog/new") {
		
		const isloginResult = islogin(req);
		if(isloginResult){
			return islogin;
		}
		
		const blogData = req.body;
		const blogResult = newBlog(blogData);
		return blogResult.then(e => {
			return new SuccModel(e);
		});

	}
	// 删除博客
	if (method === "POST" && req.path === "/api/blog/del") {
		// return new SuccModel(delBlog(id))
		const isloginResult = islogin(req);
		if(isloginResult){
			return islogin;
		}
		
		let author = req.session.username;
		let delResult = delBlog(id,author).then(e=>{
			if(e){
				return new SuccModel(e);
			}else{
				return new ErrModel();
			}
		});
		return delResult;
	}
	
	// 更新博客
	if (method === "POST" && req.path === "/api/blog/updata") {
		const isloginResult = islogin(req);
		if(isloginResult){
			return islogin;
		}
		
		const updataResult = updataBlog(id, req.body).then(e=>{
			if(e){
				return new SuccModel(e);
			}else{
				return new ErrModel();
			}
		});
		return updataResult;
	}
};

module.exports = blogRouter;
